package com.lbs.jiepiaisi.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.lbs.jiepiaisi.R;
import com.lbs.jiepiaisi.base.BaseActivity;
import com.lbs.jiepiaisi.base.ErrorException;
import com.lbs.jiepiaisi.base.ProgressObserver;
import com.lbs.jiepiaisi.bean.EquipBean;
import com.lbs.jiepiaisi.bean.TracingBean;
import com.lbs.jiepiaisi.config.Api;
import com.lbs.jiepiaisi.manager.SharePreferenceManager;
import com.lbs.jiepiaisi.manager.TrackPoiOverlay;
import com.lbs.jiepiaisi.utils.Constant;
import com.lbs.jiepiaisi.utils.RxSchedulers;
import com.lbs.jiepiaisi.utils.WindowSizeUtil;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * 时间：2017/9/14 15:11
 * 作用：实时跟踪
 */

public class TracingActivity extends BaseActivity implements AMap.InfoWindowAdapter,
        AMap.OnMarkerClickListener, AMap.OnMapClickListener, AMap.OnMyLocationChangeListener, GeocodeSearch.OnGeocodeSearchListener {

    public static final String TAG = "TracingActivity";
    private MapView mapView;//地图
    public AMap aMap;//地图控制器对象
    private String eqNo;//设备编号
    private List<TracingBean.Result> results;
    private ImageView image_location_car;
    private ImageView image_location_my;
    private ImageView image_location_all;
    private TextView text_time;
    private TextView text_location;
    private List<LatLng> latLngs = new ArrayList<>();//经纬度集合
    private List<LatLng> routeLatLngs = new ArrayList<>();//经纬度集合
    private LatLng myLatlng;
    private Marker showMarker = null;
    private ArrayList<Marker> markers = new ArrayList();
    private String status = "正在获取";
    private String name;
    public SharePreferenceManager mSharePreference = null;
    private ImageView iamge_trace_car;

    TrackPoiOverlay trackPoiOverlay;
    //焦点状态 0个人位置 1车辆位置 2总览
    private int flag = 1;

    private View mInfoView;
    private boolean isFirst = true;
    private float currentZoom = 13;
    private boolean isShowDialog = true;

    private RegeocodeQuery eqRegeocodeQuery;
    private GeocodeSearch eqGeocodeSearch;//逆地理编码转换对象

    private CountDownTimer timer;

    public void initGeocodeSearch(){
        eqGeocodeSearch = new GeocodeSearch(this);
        eqGeocodeSearch.setOnGeocodeSearchListener(this);
    }

    private void countDown() {

        timer = new CountDownTimer(10 * 1000, 1000) {

            @SuppressLint("SetTextI18n")
            @Override
            public void onTick(long millisUntilFinished) {
                text_time.setText(millisUntilFinished / 1000 + "s后刷新");
            }

            @Override
            public void onFinish() {
                countDown();
                refreshStatus();
                refreshTracing();
            }
        }.start();
    }

    public void refreshStatus(){
        Api.getInstance().createService()
                .loadEquipList("",1,1,"",eqNo)
                .compose(RxSchedulers.observableIO2Main(this))
                .subscribe(new ProgressObserver<EquipBean>(this, false) {
                    @Override
                    public void onSuccess(EquipBean result) {
                        List<EquipBean.Result.Items> item = result.getResult().get(0).getItems();
                        status = item.get(0).getCnStatus();
                    }

                    @Override
                    public void onFailure(ErrorException e) {
                        Log.e("HHHHHHH",e.getMsg());
                    }
                });
    }

    public void refreshTracing() {
        Api.getInstance().createService()
                .loadTracing(eqNo)
                .compose(RxSchedulers.observableIO2Main(this))
                .subscribe(new ProgressObserver<TracingBean>(this,false) {
                    @Override
                    public void onSuccess(TracingBean result) {

                        if (result == null || result.getResult().size() == 0){
                            text_location.setText("暂无位置");
                            return;
                        }

                        results = result.getResult();

                        LatLonPoint latLonPoint = new LatLonPoint(result.getResult().get(0).getGdLat(), result.getResult().get(0).getGdLng());
                        eqRegeocodeQuery = new RegeocodeQuery(latLonPoint, 200,GeocodeSearch.AMAP);
                        eqGeocodeSearch.getFromLocationAsyn(eqRegeocodeQuery);

                        loadView();
                        markPointsOnMap();
                        markCarsOnMap(results);
                        showMarkDialog();
                        if (isFirst && myLatlng != null) {
                            moveCamera();
                            isFirst = false;
                        }
                    }

                    @Override
                    public void onFailure(ErrorException e) {

                    }
                });
    }

    @Override
    public void onMyLocationChange(Location location) {
        if (location != null) {
            myLatlng = new LatLng(location.getLatitude(), location.getLongitude());
        }
    }

    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
        if (i == 1000) {
            if (regeocodeResult.getRegeocodeQuery() == eqRegeocodeQuery) {
                if (regeocodeResult != null && regeocodeResult.getRegeocodeAddress() != null
                        && regeocodeResult.getRegeocodeAddress().getFormatAddress() != null) {
                    RegeocodeAddress info = regeocodeResult.getRegeocodeAddress();

                    String eqPo;

                    if (info.getPois().size() == 0) {
                        eqPo = info.getFormatAddress();
                    } else {
                        PoiItem poi = info.getPois().get(0);
                        String poiName = poi.getTitle();

                        if (info.getFormatAddress().contains(poiName)) {
                            poiName = "";
                        }

                        eqPo = info.getFormatAddress() +
                                poiName + " " +
                                poi.getDirection() + " " +
                                poi.getDistance() + "米";
                    }

                    text_location.setText(eqPo);
                    Log.e("ppp设备位置",eqPo);
                }
            }
        }
    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {}

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isTemplate = true;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tracing);
        countDown();
        titleView.setText("实时跟踪");
        templateButtonLeft.setImageResource(R.mipmap.back_white);
        mapView = findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);// 此方法必须重写
        Intent intent = getIntent();
        eqNo = intent.getStringExtra("eqNo");
        name = intent.getStringExtra("ownerName");

        getExras();
        findView();
        setListener();
        initGPS();
        refreshStatus();
        refreshTracing();
        initGeocodeSearch();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    //加载网络数据
    private void getExras() {
        if (aMap == null) {
            aMap = mapView.getMap();
            aMap.getUiSettings().setRotateGesturesEnabled(false);
            aMap.setOnMarkerClickListener(this);// 设置点击marker事件监听器
            aMap.setInfoWindowAdapter(this);// 设置自定义InfoWindow样式
        }
        if (aMap != null) {
            aMap.clear(true);
        }
        if (showMarker != null) {
            showMarker.remove();
        }
        if (markers != null) {
            markers.clear();
        }
        latLngs.clear();
    }

    private void findView() {
        image_location_car = findViewById(R.id.image_location_car);
        image_location_my = findViewById(R.id.image_location_my);
        image_location_all = findViewById(R.id.image_location_all);
        text_time = findViewById(R.id.text_time);
        iamge_trace_car = findViewById(R.id.iamge_trace_car);
        text_location = findViewById(R.id.text_location);
    }

    private void setListener() {
        image_location_car.setOnClickListener(v -> {
            flag = 1;
            moveCamera();
            closeMarkDialog();
            showMarkDialog();
        });

        image_location_my.setOnClickListener(v -> {
            flag = 0;
            moveCamera();
            closeMarkDialog();
            showMarkDialog();
        });

        image_location_all.setOnClickListener(v -> {
            flag = 2;
            moveCamera();
            closeMarkDialog();
            showMarkDialog();
        });

        //追车
        iamge_trace_car.setOnClickListener(v -> {
            Intent intent = new Intent(mContext, AccountChaseCarAcitivty.class);
            intent.putExtra(Constant.ACCOUNT_NAVIGATION, (Serializable)results);
            startActivity(intent);
        });

        aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {

            }

            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {
                currentZoom = cameraPosition.zoom;
            }
        });
    }

    private void initGPS() {
        LocationManager locationManager = (LocationManager) this
                .getSystemService(Context.LOCATION_SERVICE);
        // 判断GPS模块是否开启
        if (!locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            AlertDialog.Builder dialog = new AlertDialog.Builder(this);
            dialog.setMessage("请打开GPS");
            dialog.setPositiveButton("确定",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
                            // 转到手机设置界面，用户设置GPS
                            Intent intent = new Intent(
                                    Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivityForResult(intent, 0); // 设置完成后返回到原来的界面

                        }
                    });
            dialog.setNeutralButton("取消", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface arg0, int arg1) {
                    arg0.dismiss();
                    finish();
                }
            });
            dialog.show();
        } else {
            //自定义系统小蓝点
            setUpMap();
        }
    }

    public void setUpMap() {
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER);
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory
                .fromResource(R.mipmap.point4));// 设置小蓝点的图标
        myLocationStyle.strokeColor(Color.BLACK);// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(100, 0, 0, 180));// 设置圆形的填充颜色
        myLocationStyle.strokeWidth(1.0f);// 设置圆
        myLocationStyle.showMyLocation(true);
        aMap.setMyLocationStyle(myLocationStyle);
        aMap.setOnMyLocationChangeListener(this);
        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        aMap.setOnMapClickListener(this);
    }

    /**
     * 设置自定义InfoWindow样式的回调方法
     * infocontents事件回调
     * 注意：API优先回调getInfoWindow ，如果返回的是null，会再回调getInfoContents。
     */
    @Override
    public View getInfoWindow(Marker marker) {
        int possion = Integer.valueOf(marker.getTitle());
        return getInfoView(possion);
    }

    /**
     * 设置自定义InfoWindow样式的回调方法
     * infowindow事件回调
     */
    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    private View getInfoView(final int possion) {
        mInfoView = LayoutInflater.from(mContext).inflate(R.layout.layout_marker_tracing_infowindow, null);
        loadView();
        return mInfoView;
    }

    private void loadView() {
        if (mInfoView == null) {
            return;
        }

        TracingBean.Result result = results.get(0);

        ((TextView) mInfoView.findViewById(R.id.tv_driverName)).setText(name);
        ((TextView) mInfoView.findViewById(R.id.tv_eqno)).setText(result.getEqNo());
        ((TextView) mInfoView.findViewById(R.id.tv_time)).setText(result.getImportTime());
        ((TextView) mInfoView.findViewById(R.id.tv_type)).setText(result.getPostType());
        ((TextView) mInfoView.findViewById(R.id.tv_dir)).setText(getDir(result.getDir()));
        ((TextView) mInfoView.findViewById(R.id.tv_speed)).setText(result.getSpeed() + " km/h");
        ((TextView) mInfoView.findViewById(R.id.tv_status)).setText(status.replaceAll(" ",""));
    }

    public String getDir(float dir){
        if(dir == 0 || dir == 360){ return "正北"; }
        if(dir > 0  && dir < 90){ return "东北"; }
        if(dir == 90){ return "正东"; }
        if(dir > 90  && dir < 180){ return "东南"; }
        if(dir == 180){ return "正南"; }
        if(dir > 180  && dir < 270){ return "西南"; }
        if(dir == 270){ return "正西"; }
        if(dir > 270  && dir < 360){ return "西北"; }
        return "";
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        // 设置地图中心点在屏幕的位置
        aMap.setPointToCenter(WindowSizeUtil.getWidth(mContext) / 2, WindowSizeUtil.getHeight(mContext) / 5 * 3);
        showMarker = marker;
        isShowDialog = true;
        if (showMarker.isInfoWindowShown()) {
            closeMarkDialog();
        } else {
           showMarker.showInfoWindow();
        }
        aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(marker.getPosition().latitude, marker.getPosition().longitude)));
        return true;//返回:true:表示点击marker后,marker不会移动到地图中心；返回false表示点击marker后,marker会自动移动到地图中心。
    }

    @Override
    public void onMapClick(LatLng latLng) {
        Log.e("TAG", "地图被点击了！！！！");
        if (null != showMarker) {
            isShowDialog = false;
            showMarker.hideInfoWindow();//这个是隐藏infowindow窗口的方法
        }
    }

    /**
     * 设置Markers方法
     */
    private void markCarsOnMap(List<TracingBean.Result> items) {
        List<BitmapDescriptor> b = TrackPoiOverlay.getBitmap(items, mContext, name, status);//设置图片状态
        trackPoiOverlay = TrackPoiOverlay.instance(aMap, items, b, (WindowSizeUtil.getWidth(mContext)) / 8);
        trackPoiOverlay.addToMap();
    }

    /**
     * 画线
     */
    private void markPointsOnMap() {
        aMap.clear(true);
        //画移动轨迹
        markLines();
        //画两点之间的线
        markTwoPoint();
    }

    private void markLines() {
        if(results != null  && results.size() > 0){
            LatLngBounds.Builder var1 = LatLngBounds.builder();
            LatLng newLatlng = new LatLng(results.get(0).getGdLat(), results.get(0).getGdLng());//获得网络数据
            routeLatLngs.add(newLatlng);
            var1.include(newLatlng);
            aMap.addPolyline(new PolylineOptions().color(Color.RED)
                    .addAll(routeLatLngs).width(10));
        }
    }

    private void markTwoPoint() {
        latLngs = new ArrayList();
        LatLngBounds.Builder var1 = LatLngBounds.builder();
        //当前位置坐标点
//        LatLng myLatlng = new LatLng(lat, lon);
        if(results != null && results.size() > 0){
            //设备坐标点
            LatLng eqLatlng = new LatLng(results.get(0).getGdLat(), results.get(0).getGdLng());
            latLngs.add(eqLatlng);
        }
        //添加当前坐标点与设备坐标点
        if (myLatlng != null) {
            latLngs.add(myLatlng);
        }

        var1.include(myLatlng);
        //画线
        aMap.addPolyline(new PolylineOptions().color(Color.BLUE)
                .addAll(latLngs).width(5));
        //移动到当前线
        moveCamera();
    }

    private void moveCamera() {
        double curLat = 0;
        double curLng = 0;
        if (flag == 0) {
            aMap.moveCamera(CameraUpdateFactory.zoomTo(currentZoom));
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(myLatlng));
        } else if (flag == 1) {
            if(results != null && results.size() > 0){
                curLat = results.get(0).getGdLat();
                curLng = results.get(0).getGdLng();
            }

            aMap.moveCamera(CameraUpdateFactory.zoomTo(currentZoom));
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(curLat, curLng)));
        } else {
            zoomToSpan();
        }
    }

    private void showMarkDialog() {
        // 设置地图中心点在屏幕的位置
        if(trackPoiOverlay != null){
            //aMap.setPointToCenter(WindowSizeUtil.getWidth(mContext) / 2, WindowSizeUtil.getHeight(mContext) / 5 * 3);
            showMarker = trackPoiOverlay.getMarker();
            if(showMarker != null && !showMarker.isInfoWindowShown() && isShowDialog){
                showMarker.showInfoWindow();
            }
        }
    }

    private void closeMarkDialog() {
        showMarker = trackPoiOverlay.getMarker();
        if (showMarker != null && showMarker.isInfoWindowShown()) {
            showMarker.hideInfoWindow();
        }
    }

    /**
     * 移动镜头到当前的视角。
     */
    private void zoomToSpan() {
        LatLngBounds var1 = getAllMarkers();
        this.aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(var1, 400));
    }

    private LatLngBounds getAllMarkers() {
        LatLngBounds.Builder var1 = LatLngBounds.builder();
        var1.include(myLatlng);
        if(results != null && results.size() > 0){
            var1.include(new LatLng(results.get(0).getGdLat(), results.get(0).getGdLng()));
        }
        return var1.build();
    }

}
